<template>
  <a-modal
    class="db-table-form"
    :title="title"
    :visible="visible"
    :maskClosable="false"
    :keyboard="false"
    :width="480"
    :confirmLoading="confirmLoading"
    @cancel="handleCancel"
    @ok="handleSubmit"
  >
    <a-form-model ref="form" :model="form" :label-col="labelCol" :wrapper-col="wrapperCol">
      <a-form-model-item
        :label="$t('common.name')"
        prop="name"
        :rules="[
          {
            validator: validator.nameValidator,
            trigger: 'change'
          },
          {
            required: true,
            message: $t('common.emptyErr', { name: $t('common.name').toLowerCase() }),
            trigger: 'change'
          }
        ]"
      >
        <s-input :limit="64" v-model.trim="form.name" />
      </a-form-model-item>
      <a-form-model-item
        :label="$t('edgeManagement.edgeConfig.url')"
        prop="heartbeatUrl"
        :rules="[
          {
            required: true,
            message: $t('common.emptyErr', { name: $t('edgeManagement.edgeConfig.url').toLowerCase() }),
            trigger: 'change'
          },
          {
            pattern: URL_REG,
            message: this.$t('common.illegalInput', { name: this.$t('edgeManagement.edgeConfig.url') }),
            trigger: 'change'
          }
        ]"
      >
        <s-input :limit="255" v-model.trim="form.heartbeatUrl" />
      </a-form-model-item>
      <a-form-model-item
        :label="$t('edgeManagement.edgeConfig.number')"
        prop="number"
        :rules="[
          {
            required: true,
            message: $t('common.emptyErr', { name: $t('edgeManagement.edgeConfig.number').toLowerCase() }),
            trigger: 'change'
          }
        ]"
      >
        <s-input :limit="100" v-model.trim="form.number" />
      </a-form-model-item>
      <a-form-model-item
        :label="$t('common.username')"
        prop="userName"
        :rules="[
          {
            required: true,
            message: $t('common.emptyErr', { name: $t('common.username').toLowerCase() }),
            trigger: 'change'
          }
        ]"
      >
        <s-input :limit="64" v-model.trim="form.userName" />
      </a-form-model-item>
      <a-form-model-item
        :label="$t('common.password')"
        prop="password"
        :rules="[
          {
            required: true,
            message: $t('common.emptyErr', { name: $t('common.password').toLowerCase() }),
            trigger: 'change'
          }
        ]"
      >
        <a-input-password v-model="form.password" />
      </a-form-model-item>
      <a-form-model-item :label="$t('common.description')" prop="description">
        <s-textarea :limit="255" v-model.trim="form.description" />
      </a-form-model-item>
    </a-form-model>
  </a-modal>
</template>

<script>
import { SInput, STextarea } from '@/components'
import { asyncValidateMixin } from '@/utils/mixin'
import { URL_REG } from '@/utils/regExp'
import {
  postEdgemanagement,
  putEdgemanagement,
  getEdgemanagementVerification
} from '@/api/edgeManagement/EdgeManagementController'

export default {
  name: 'EdgeForm',
  mixins: [asyncValidateMixin],
  components: {
    SInput,
    STextarea
  },
  data () {
    return {
      visible: false,
      confirmLoading: false,
      type: 'add',
      labelCol: {
        sm: {
          span: 6
        }
      },
      wrapperCol: {
        sm: {
          span: 16
        }
      },
      form: {
        comment: '',
        heartbeatUrl: '',
        name: '',
        number: '',
        password: '',
        userName: ''
      },
      URL_REG
    }
  },
  computed: {
    title () {
      return this.type === 'add' ? this.$t('button.add') : this.$t('button.edit')
    }
  },
  methods: {
    initValidate (id) {
      this.$_asyncValidateMixin_init([
        {
          fieldName: 'name',
          caller: getEdgemanagementVerification,
          extraParams: {
            id
          }
        }
      ])
    },
    add () {
      this.type = 'add'
      this.visible = true
      this.initValidate()
    },
    edit (record) {
      this.type = 'edit'
      this.form = {
        ...record,
        password: ''
      }
      this.visible = true
      this.initValidate(this.form.id)
    },
    handleCancel () {
      this.form = {
        comment: '',
        heartbeatUrl: '',
        name: '',
        number: '',
        password: '',
        userName: ''
      }
      this.visible = false
      this.$refs.form.resetFields()
      this.$_asyncValidateMixin_resetFields()
    },
    handleSubmit () {
      if (!this.canSubmit) {
        return
      }
      this.confirmLoading = true
      const fieldNames = this.$_asyncValidateMixin_fieldsFilter({
        name: '',
        heartbeatUrl: '',
        number: '',
        password: '',
        userName: ''
      })
      const validatePromise = fieldNames.map(fieldName => {
        const p = new Promise((resolve, reject) => {
          this.$refs.form.validateField(fieldName, errorMessage => {
            if (!errorMessage) {
              resolve()
            } else {
              reject(errorMessage)
            }
          })
        })
        return p
      })
      Promise.all(validatePromise)
        .then(() => {
          this.confirmLoading = false
          this.editData()
        })
        .catch(() => {
          this.confirmLoading = false
        })
    },
    editData () {
      const apiFun = this.type === 'add' ? postEdgemanagement : putEdgemanagement
      apiFun(this.form)
        .then(res => {
          this.$message.success('操作成功')
          this.$emit('ok',this.type)
          this.handleCancel()
        })
        .finally(() => {
          this.confirmLoading = false
        })
    }
  }
}
</script>
<style lang="less"></style>
